/*****************************************************************//**
 * \file   noniso.c
 * \brief  Convert string integers to each other
 * 
 * \author monster
 * \date   April 2024
 *********************************************************************/
#include "stdlib_noniso.h"
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <stdio.h>

/**
 * Reverse string buffer
 * @param begin Pointer to string head
 * @param end Pointer to string tail
 */
static void reverse(char *begin, char *end) {
    char *is = begin;
    char *ie = end - 1;
    while (is < ie) {
        char tmp = *ie;
        *ie = *is;
        *is = tmp;
        ++is;
        --ie;
    }
}


char *dtostrf(double value, signed int width, unsigned int prec, char *str) {
    if (str == NULL) return NULL;

    char fmt[20];
    snprintf(fmt, sizeof(fmt), "%%%d.%df", width, prec);
    sprintf(str, fmt, value);
    return str;
}


char *ltoa(long value, char *string, int radix) {
    if (radix < 2 || radix > 16) {
        *string = 0;
        return string;
    }

    char *out     = string;
    long quotient = value > 0 ? value : -value;

    do {
        const long tmp = quotient / radix;
        *out = "01234567890abcdef"[quotient - (tmp * radix)];
        ++out;
        quotient = tmp;
    } while (quotient);

    /* apply negative sign */
    if (value < 0)
        *out++ = '-';

    reverse(string, out);
    *out = 0;
    return string;
}


char *ultoa(unsigned long value, char *string, int radix) {
    if (radix < 2 || radix > 16) {
        *string = 0;
        return string;
    }

    char *out     = string;
    unsigned long quotient = value > 0 ? value : -value;

    do {
        const unsigned long tmp = quotient / radix;
        *out = "01234567890abcdef"[quotient - (tmp * radix)];
        ++out;
        quotient = tmp;
    } while (quotient);

    reverse(string, out);
    *out = 0;
    return string;
}

#ifndef __GNUC__

char *utoa(unsigned long value, char *str, int radix) {
    return ultoa(value, str, radix);
}



#endif
